package com.gnerv.cms.controller;

import com.gnerv.cms.common.Result;
import com.gnerv.cms.dto.SendMessageDTO;
import com.gnerv.cms.dto.UserLoginDTO;
import com.gnerv.cms.store.SseEmitterStorage;
import com.gnerv.cms.utils.ShiroUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@Slf4j
@Api(tags = "基础平台-消息推送")
@CrossOrigin
@Controller
@RequestMapping("/api/manage/sse")
public class SseController {

    @RequestMapping(path = "/register", produces = MediaType.TEXT_EVENT_STREAM_VALUE, method = RequestMethod.GET)
    public SseEmitter handle() {
        UserLoginDTO userLoginDTO = ShiroUtils.getLoginUser();
        SseEmitter sseEmitter = new SseEmitter();
        SseEmitterStorage.SSE_EMITTERS.put(userLoginDTO.getUkId(), sseEmitter);
        return sseEmitter;
    }

    @RequestMapping(value = "/send", produces = MediaType.TEXT_EVENT_STREAM_VALUE, method = RequestMethod.POST)
    @ResponseBody
    public Result send(@RequestBody SendMessageDTO sendMessageDTO) throws IOException {
        sendMessageDTO.setFromUser(ShiroUtils.getLoginUser().getUkId());
        SseEmitter sseEmitter = SseEmitterStorage.SSE_EMITTERS.get(sendMessageDTO.getToUser());
        if (ObjectUtils.isEmpty(sseEmitter)) {
            log.info("人不在");
        }
        sseEmitter.send(sendMessageDTO.getContent(), MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE));
        return Result.response();
    }

}
